<template>
  <el-form v-if="control" ref="controlEdit" :model="control" :rules="rules" label-width="120px">
    <el-card header="基础配置">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="标题" prop="Name">
            <el-input v-model="control.Name" :maxlength="50" placeholder="标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="Show">
            <el-input v-model="control.Show" :maxlength="50" placeholder="说明" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="占用宽度" prop="WidthRatio">
            <el-select v-model="control.WidthRatio" style="width: 100%;" placeholder="占用宽度">
              <el-option label="1/6" :value="6" />
              <el-option label="1/5" :value="5" />
              <el-option label="1/4" :value="4" />
              <el-option label="1/3" :value="3" />
              <el-option label="1/2" :value="2" />
              <el-option label="2/3" :value="23" />
              <el-option label="整行" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="占用高度(格)" prop="HeightGrid">
            <el-input-number
              v-model="control.HeightGrid"
              :min="5"
              :max="30"
              :step="1"
              :precision="0"
              style="width: 100%;"
              placeholder="占用高度(格)"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
    <el-tabs :value="active" type="border-card" style="margin-top: 10px;" @tab-click="tabSwitch">
      <el-tab-pane label="数据源配置" name="form">
        <el-form-item label="选择数据源" prop="FormId">
          <formInput v-model="control.FormId" placeholder="选择表单" :form-type="[3]" @change="initForm" />
        </el-form-item>
        <editSelect v-model="control.Selects" :limit-form-id="limitFormId" :disabled="control.FormId == null" :selects="selects" @change="initSelect" />
      </el-tab-pane>
      <el-tab-pane label="查询条件" name="where">
        <pageFilterEdit ref="pageFilter" :form-id="control.FormId" :items="control.Where" />
      </el-tab-pane>
      <el-tab-pane label="排序和分组" name="groupBy">
        <el-form-item label="分组字段">
          <el-select
            v-model="control.GroupBy"
            placeholder="选择分组字段"
            style="width: 100%;"
            :multiple="true"
            @change="() => control.OrderBy = []"
          >
            <el-option v-for="item in filterGroupBy()" :key="item.Alias" :label="item.Label" :value="item.Alias" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="control.GroupBy && control.GroupBy.length > 0" label="再次筛选">
          <el-row :gutter="2">
            <el-col :span="6">
              <el-select
                v-model="having.ColId"
                placeholder="选择筛选字段"
                clearable
                style="width: 100%;"
              >
                <el-option v-for="item in cols" :key="item.ColId" :label="item.Label" :value="item.ColId" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <enumItem
                v-model="having.FuncType"
                :dic-key="EnumDic.PageFuncType"
                placeholder="函数类型"
                :multiple="false"
                sys-head="form"
              />
            </el-col>
            <el-col :span="4">
              <enumItem
                v-model="having.Mode"
                :dic-key="EnumDic.PageFilterMode"
                placeholder="匹配类型"
                sys-head="form"
              />
            </el-col>
            <el-col :span="9">
              <filterValueSet v-model="having.Value" :mode="having.Mode" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="排序" prop="OrderBy">
          <el-row v-for="(i, index) in control.OrderBy" :key="index" :gutter="8">
            <el-col :span="6">
              <el-select v-model="i.Col" style="width: 100%;" placeholder="排序列">
                <el-option v-for="item in filterOrderBy()" :key="item.Alias" :label="item.Label" :value="item.Alias" />
              </el-select>
            </el-col>
            <el-col :span="16">
              <el-switch
                v-model="i.IsDesc"
                active-text="降序"
                inactive-text="升序"
              />
            </el-col>
          </el-row>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addOrderBy">添加</el-button>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
  </el-form>
</template>

<script>
import formInput from '@/customForm/components/form/formInput.vue'
import editSelect from './editSelect.vue'
import { EnumDic } from '@/customForm/config/formConfig'
import pageFilterEdit from './pageFilterEdit.vue'
import { GetColumns } from '@/customForm/api/form'
import filterValueSet from '@/customForm/views/formView/components/filterValueSet.vue'
export default {
  components: {
    formInput,
    editSelect,
    pageFilterEdit,
    filterValueSet
  },
  props: {
    contentWidth: {
      type: Number,
      default: null
    },
    source: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      EnumDic,
      control: null,
      ver: 1,
      selects: [],
      limitFormId: [],
      cols: [],
      selectList: [],
      having: {},
      funcType: [0, 6, 7, 8, 9, 10, 11],
      active: 'form',
      rules: {
        Name: [
          {
            required: true,
            message: '标题不能为空！',
            trigger: 'blur'
          }
        ],
        FormId: [
          {
            required: true,
            message: '请选择数据源！',
            trigger: 'blur'
          }
        ],
        HeightGrid: [
          {
            required: true,
            message: '请选择占用高度！',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    source: {
      handler(val) {
        if (val) {
          this.resetForm()
        } else {
          this.control = null
        }
      },
      immediate: true
    }
  },
  mounted() { },
  methods: {
    initForm() {
      this.limitFormId = this.control.FormId ? [this.control.FormId] : null
      if (this.control.FormId) {
        this.initColumns()
      }
    },
    addOrderBy() {
      this.control.OrderBy.push({
        Col: null,
        IsDesc: false
      })
    },
    initSelect(list) {
      const datas = []
      list.forEach(c => {
        if (c.IsGroup) {
          c.Children.forEach(a => {
            datas.push({
              Alias: a.Alias,
              Label: a.Label,
              FuncType: a.FuncType,
              ColId: c.ColumnId
            })
          })
        } else {
          datas.push({
            Alias: c.Alias,
            Label: c.Label,
            FuncType: c.FuncType,
            ColId: c.ColumnId
          })
        }
      })
      this.selectList = datas
    },
    async initColumns() {
      const list = await GetColumns({
        FormId: this.control.FormId,
        ShowMode: [0]
      })
      this.cols = list.map(c => {
        return {
          ColId: c.Id,
          Alias: c.Name,
          Label: c.Label
        }
      })
    },
    filterOrderBy() {
      if (this.control.GroupBy && this.control.GroupBy.length > 0) {
        return this.selectList
      }
      return this.cols
    },
    filterGroupBy() {
      if (this.selectList.length === 0) {
        return []
      }
      return this.selectList.filter(a => this.funcType.includes(a.FuncType))
    },
    tabSwitch(e) {
      if (e.name === 'form') {
        this.active = e.name
      } else if (this.control.FormId == null || this.control.Selects == null || this.control.Selects.length === 0) {
        return
      }
      this.active = e.name
    },
    resetForm() {
      this.active = 'form'
      const set = {
        Id: this.source.Id,
        Name: this.source.Name,
        WidthRatio: this.source.WidthRatio,
        HeightGrid: this.source.HeightGrid,
        Show: this.source.Show,
        FormId: null,
        Selects: null,
        Where: [],
        OrderBy: [],
        GroupBy: []
      }
      if (this.source.ControlConfig && this.source.ControlConfig.CensusTable) {
        const conf = this.source.ControlConfig.CensusTable
        set.FormId = conf.FormId
        set.OrderBy = []
        if (conf.OrderBy) {
          for (const i in conf.OrderBy) {
            if (i != null) {
              set.OrderBy.push({
                Col: i,
                IsDesc: conf.OrderBy[i]
              })
            }
          }
        }
        this.having = conf.Having ?? {}
        this.selects = conf.Selects ?? []
        set.GroupBy = conf.GroupBy ?? []
        set.Where = conf.Where ?? []
        this.limitFormId = conf.FormId ? [conf.FormId] : null
      } else {
        this.having = {}
      }
      this.control = set
      if (set.FormId != null) {
        this.initColumns()
      }
    },
    save() {
      const that = this
      return new Promise((resolve, reject) => {
        that.$refs['controlEdit'].validate((valid) => {
          if (valid) {
            const data = that.getData()
            if (data == null) {
              reject()
              return
            }
            resolve(data)
          } else {
            reject()
            return false
          }
        })
      })
    },
    getData() {
      let where = null
      if (this.$refs.pageFilter != null) {
        where = this.$refs.pageFilter.getValue()
        if (where.isError) {
          return null
        }
      }
      const data = {
        Name: this.control.Name,
        WidthRatio: this.control.WidthRatio,
        HeightGrid: this.control.HeightGrid,
        Show: this.control.Show,
        ControlConfig: {
          CensusTable: null
        }
      }
      const orderBy = {}
      this.control.OrderBy.forEach(c => {
        if (c.Col != null) {
          orderBy[c.Col] = c.IsDesc
        }
      })
      const config = {
        FormId: this.control.FormId,
        OrderBy: orderBy,
        Having: this.control.Having,
        Selects: this.control.Selects,
        GroupBy: this.control.GroupBy,
        Where: where.rows
      }
      data.ControlConfig.CensusTable = config
      return data
    }
  }
}
</script>
<style scoped>
.controlView {
    width: 100%;
    height: 600px;
    line-height: 600px;
    overflow-x: auto;
    overflow-y: hidden;
    padding: 10px;
}
.controlView .el-card {
    display: inline-block;
    line-height: normal;
}
.header {
    height: 30px;
    line-height: 30px;
    border-left: 4px solid #409eff;
    text-indent: 5px;
    font-size: 1.2em;
    margin-bottom: 5px;
}
</style>
